package app.controllers;

import app.models.system.Resource;
import app.models.system.Role;
import app.models.system.User;
import com.google.common.base.Strings;
import com.ifonly.interceptor.Intercepts;
import com.ifonly.mvc.ActionKey;
import com.ifonly.mvc.Controller;
import com.ifonly.mvc.methods.Post;
import com.ifonly.security.IfonlySecurity;
import com.ifonly.security.SecurityEntry;
import com.ifonly.security.SecurityInfo;

import java.util.List;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-16 16:07
 * @since JDK 1.6
 */
public class LoginController extends Controller {

    @ActionKey("/")
    public void index() {
        render("/login");
    }

    @ActionKey("/login")
    @Intercepts(Post.class)
    public void login() {
        String username = getParam("username");
        String password = getParam("password");
        /**
         * 记住我 需要设置的 Cookie 的内容不能太长了, 当前项目不支持, 因为设置的内容超过限制
         */
        boolean rememberMe = !Strings.isNullOrEmpty(getParam("rememberMe"));
        try {
            IfonlySecurity.login(username, password, rememberMe);
            SecurityEntry<Long, SecurityInfo<User, Role, List<Resource>>> securityEntry = IfonlySecurity.getSecurityEntry();
            SecurityInfo<User, Role, List<Resource>> info = securityEntry.getInfo();
            List<Resource> resources = info.getP();
            Role role = info.getR();
            User user = info.getU();

            setSessionAttr("loginUser", user);
            setSessionAttr("loginRole", role);
            setSessionAttr("loginResources", resources);

            setAttr("userName", user.getString("username"));
            redirect("/main");
        } catch (RuntimeException e) {
            e.printStackTrace();
            logger.error("登录失败", e);
            setAttr("message", e.getMessage());
            render("/login");
        }
    }

}
